<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-button type="primary" @click="rolesDialogVisible = true"
        >添加角色</el-button
      >
      <!-- 添加角色的对话框 -->
      <el-dialog
        title="添加角色"
        :visible.sync="rolesDialogVisible"
        width="50%"
        @close="rolesDialgClose"
      >
        <!-- 内容主体 -->
        <el-form
          :model="rolesForm"
          :rules="rolesFormRules"
          ref="rolseFormref"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="rolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="rolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="rolesDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addroles">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 权限列表 -->
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['dbbottom', i1 === 0 ? 'dbtop' : '', 'v']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeById(scope.row, item1.id)">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限和三级 -->
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  :class="[i2 == 0 ? '' : 'dbtop', 'v']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-row>
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="bianji(scope.row.id)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="shanchu(scope.row.id)"
                >删除</el-button
              >
              <el-button
                type="warning"
                icon="el-icon-s-tools"
                size="mini"
                @click="showSet(scope.row)"
                >分配权限</el-button
              >
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 编辑对话框 -->
    <el-dialog title="修改角色" :visible.sync="bianDialogVisible" width="50%">
      <!-- 内容主体 -->
      <el-form
        :model="bianjis"
        :rules="rolesFormRules"
        ref="bianFormref"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="bianjis.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="bianjis.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="bianDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="bianroles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="showDialogVisible" width="50%">
      <!-- 内容主体 -->
      <el-tree
        :data="showList"
        show-checkbox
        node-key="id"
        default-expand-all="true"
        :default-checked-keys="treeShow"
        :props="treeProps"
        ref="treeRef"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="showroles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 获取权限列表
      rolesList: [],
      // 添加角色对话框的显示和隐藏
      rolesDialogVisible: false,
      // 添加角色列表
      rolesForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色验证
      rolesFormRules: {
        roleName: [
          {
            required: true,
            message: '请输入角色名',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          {
            required: true,
            message: '请输入角色描述',
            trigger: 'blur'
          }
        ]
      },
      // 编辑对话框的显示和隐藏
      bianDialogVisible: false,
      // 编辑角色列表
      bianjis: {},
      // 分配权限对话框的显示和隐藏
      showDialogVisible: false,
      // 所有权限的数据
      showList: [],
      // 树形控件的绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认勾选id的数组
      treeShow: [],
      // 当前即将分配的id
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
    },
    // 监听添加对话框的关闭事件 this.$refs[fromName]resetFields () 重置表单
    rolesDialgClose () {
      this.$refs.rolseFormref.resetFields()
    },
    // 添加表单角色
    addroles () {
      // validate 校验器  返回布尔值
      this.$refs.rolseFormref.validate(async valid => {
        if (!valid) return
        // 可以发起添加用户的请求
        const { data: res } = await this.$http.post('roles', this.rolesForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        }
        console.log(res)
        this.$message.success('添加角色成功')
        this.getRolesList()
        this.rolesDialogVisible = false
      })
    },
    // 根据id查询角色
    async bianji (id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询角色失败')
      }
      console.log(res.data)
      this.bianjis = res.data
      this.bianDialogVisible = true
    },
    // 根据id修改角色
    async bianroles () {
      const { data: res } = await this.$http.put('roles/' + this.bianjis.roleId, {
        roleName: this.bianjis.roleName,
        roleDesc: this.bianjis.roleDesc
      })
      console.log(res.data)
      if (res.meta.status !== 200) {
        return this.$message.error('修改失败')
      }
      this.bianDialogVisible = false
      this.$message.success('修改成功')
      this.getRolesList()
    },
    // 根据id删除角色
    async shanchu (id) {
      // 弹框询问是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除, 择返回字符串confirm
      // 如果用户取消删除， 则返回字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // console.log('确认删除')
      // 发送删除请求
      const { data: res } = await this.$http.delete('roles/' + id)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败！')
      }
      this.$message.success('删除用户成功')
      // 更新列表
      this.getRolesList()
    },
    async removeById (role, riid) {
      // 弹框询问是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除, 择返回字符串confirm
      // 如果用户取消删除， 则返回字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 发送删除请求
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${riid}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }
      role.children = res.data
    },
    async showSet (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限失败')
      }
      console.log(res.data)
      this.$message.success('获取权限成功')
      this.showList = res.data
      // 递归的三级节点
      this.getLeakeys(role, this.treeShow)
      this.showDialogVisible = true
    },
    // 通过递归的方式来获取所有三级节点的id
    getLeakeys (node, arr) {
      // 如果node节点不包含children，是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => this.getLeakeys(item, arr))
    },
    // 更新权限
    async showroles () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      console.log(keys)
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })

      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }

      this.$message.success('分配权限成功')
      this.getRolesList()
      this.showDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.dbtop {
  border-top: 1px solid #eee;
}

.dbbottom {
  border-bottom: 1px solid #eee;
}

.v {
  display: flex;
  align-items: center;
}
</style>
